<template>
  <div class="page-main" style="height: auto">
    <div style="padding: 25px 125px; background: #f5f5f5">
      <div class="hte-head-content">
        <span class="bold-font">我的私有组</span>
      </div>
      <div class="box" v-if="false">
        <div class="box-left">
          <!-- <div class="group-header">我的私有组</div> -->

          <div
            v-for="(item, index) of groupList"
            :key="index"
            @click="selectedGroup(item)"
            :class="group.id == item.id ? 'group-item active-group' : 'group-item'"
          >
            <a-icon type="team" />{{ item.name }}
          </div>
        </div>
        <div class="box-right">
          <div class="btn-group">
            <a-button class="hte-btn add-btn" type="primary" icon="usergroup-add" @click="addGroup"
              >添加私有组</a-button
            >
            <a-button class="hte-btn" icon="usergroup-delete" @click="addGroup">删除私有组</a-button>
            <a-button class="hte-btn add-btn" type="primary" icon="plus" @click="addUser" v-if="group.id"
              >添加成员</a-button
            >
            <a-button class="hte-btn" icon="delete" @click="delUser">删除成员</a-button>
          </div>
          <a-table
            ref="table"
            size="middle"
            :scroll="{ x: true }"
            bordered
            row-key="id"
            :columns="columns"
            :data-source="tableData"
            :pagination="ipagination"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            class="j-table-force-nowrap"
          >
            <span slot="group" slot-scope="text, record">
              {{ getGroupName(record) }}
            </span>
          </a-table>
        </div>
      </div>

      <a-layout id="components-layout-demo-fixed-sider" style="margin-top: 8px">
        <a-layout-sider :style="{ overflow: 'auto', background: '#fff' }" class="layout-left">
          <a-menu mode="inline" :selected-keys="defaultKeys" @select="selectedGroup">
            <a-menu-item :key="-1" style="height: 0"> </a-menu-item>
            <a-menu-item :key="item.id" v-for="item of groupList">
              <a-icon type="team" />
              <span class="nav-text">{{ item.name }}</span>
            </a-menu-item>
          </a-menu>
        </a-layout-sider>
        <a-layout :style="{ marginLeft: '16px', overflow: 'auto', background: '#fff' }" class="layout-left">
          <a-layout-content :style="{ margin: '24px 16px 0', overflow: 'initial' }">
            <div class="btn-group">
              <a-button class="hte-btn add-btn" type="primary" icon="usergroup-add" @click="addGroup"
                >添加私有组</a-button
              >
              <a-button class="hte-btn add-btn" type="primary" icon="plus" @click="addUser" v-if="group.id"
                >添加成员</a-button
              >
              <a-button class="hte-btn add-btn" icon="plus" @click="addCopy">批量导入</a-button>
              <a-button class="hte-btn" icon="usergroup-delete" @click="deleteGroup" v-if="group.id"
                >删除私有组</a-button
              >
              <a-button class="hte-btn" icon="delete" @click="delUser">删除成员</a-button>
              <a-button class="hte-btn" icon="circle" @click="fetchList">刷新</a-button>
            </div>
            <a-table
              ref="table"
              size="middle"
              :scroll="{ x: true }"
              bordered
              row-key="id"
              :columns="columns"
              :data-source="tableData"
              :pagination="ipagination"
              :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
              @change="pageChange"
              class="j-table-force-nowrap"
            >
              <span slot="group" slot-scope="text, record">
                {{ getGroupName(record) }}
              </span>
              <span slot="action" slot-scope="text, record">
                <a @click="delUserByrow(record.id)">删除</a>
              </span>
            </a-table>
          </a-layout-content>
        </a-layout>
      </a-layout>

      <a-modal title="添加私有组" :visible="addGroupVisible" @ok="saveGroup" @cancel="cancleSaveGroup">
        <a-form-model
          ref="groupForm"
          :model="groupModel"
          :rules="groupRule"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item label="名称" prop="name">
            <a-input v-model="groupModel.name" placeholder="请输入名称" />
          </a-form-model-item>
        </a-form-model>
      </a-modal>

      <a-modal title="添加组成员" :visible="addUserVisible" @ok="saveUser" @cancel="cancleSaveUser">
        <a-form-model
          ref="userForm"
          :model="userModel"
          :rules="userRule"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item label="成员" prop="userStr">
            <a-select
              v-model="userModel.userStr"
              mode="multiple"
              placeholder="请输入名称"
              style="width: 100%"
              :filter-option="false"
              :not-found-content="fetching ? '找不到记录' : null"
              @search="fetchUser"
              @change="selectedUser"
            >
              <a-spin v-if="fetching" slot="notFoundContent" size="small" />
              <a-select-option v-for="d in userList" :key="d.value" :value="d.value + '###' + d.label">
                {{ d.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
      <user-select ref="userSelect" @setResult="setResult" :origin-target-keys="originTargetKeys" />
    </div>
    <excel-paste
      :columnsExcel="columnsExcel"
      :exportXlsTemplateUrl="exportXlsTemplateUrl"
      :exportXlsTemplateRequestUrl="exportXlsTemplateRequestUrl"
      :excelVisible="excelVisible"
      :excelConfirmLoading="excelConfirmLoading"
      @handleOkExcel="handleOkExcel"
      @handleCancelExcel="handleCancelExcel"
    ></excel-paste>
  </div>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
export default {
  components: {
    UserSelect: () => import('@/components/tools/UserSelect'),
    ExcelPaste: () => import('@/components/excelPaste/ExcelPaste'),
  },
  data() {
    return {
      replaceFields: { children: 'children', title: 'name', key: 'id' },
      defaultKeys: [],
      originTargetKeys: [],
      columns: [
        {
          title: '组名称',
          align: 'center',
          dataIndex: 'groupId',
          scopedSlots: { customRender: 'group' },
        },
        {
          title: '成员',
          align: 'center',
          dataIndex: 'userName',
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createrUser',
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
        },
        // {
        //   title: '操作',
        //   dataIndex: 'action',
        //   align: 'center',
        //   fixed: 'right',
        //   width: 147,
        //   scopedSlots: { customRender: 'action' },
        // },
      ],
      groupList: [],
      tableData: [],
      urls: {
        list: '/lib/hteLibraryGroup/list',
        userList: '/lib/hteLibraryGroup/userList',
        saveGroup: '/lib/hteLibraryGroup/saveGroup',
        saveUser: '/lib/hteLibraryGroup/saveUser',
        addBatchUser: '/lib/hteLibraryGroup/addBatchUser',
        getUserList: '/lib/hteFileClass/getUserList',
        delUser: '/lib/hteLibraryGroup/delUser',
        delGroup: '/lib/hteLibraryGroup/delGroup',
      },
      selectedRowKeys: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      group: {},
      user: {},
      groupModel: {},
      userModel: {},
      addGroupVisible: false,
      addUserVisible: false,
      userList: [],
      fetching: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      userRule: {
        userStr: [{ required: true, message: '请选择成员', trigger: 'change' }],
      },
      groupRule: {
        name: [{ required: true, message: '请输入私有组名称', trigger: 'change' }],
      },
      groupId: '',
      exportXlsTemplateUrl: 'templates/excel/私有组导入模板.xlsx',
      exportXlsTemplateRequestUrl: '/common/exportXlsTemplate',
      excelConfirmLoading: false,
      excelVisible:false,
      excelDataSource: [],
      columnsExcel: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
          isImportExcelColumns: false,
        },
        {
          title: '组名称',
          align: 'center',
          dataIndex: 'groupName',
        },
        {
          title: '成员名称',
          align: 'center',
          dataIndex: 'userName',
        },
      ],
    }
  },
  mounted() {
    this.fetchList()
  },
  methods: {
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    fetchList() {
      this.defaultKeys = []
      this.group = {}
      getAction(this.urls.list, {}).then((res) => {
        if (res.success) {
          this.groupList = res.result
          if (res.result.length > 0) {
            let defaultGroup = res.result[0]
            this.group = defaultGroup
            this.defaultKeys = [this.group.id]
            this.fetchUserList(this.group.id)
          }
        }
      })
    },
    fetchUserList(groupId) {
      this.ipagination.id = groupId
      let param = Object.assign({}, this.ipagination)
      delete param.pageSizeOptions
      delete param.showTotal
      getAction(this.urls.userList, param).then((res) => {
        if (res.success) {
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
          this.tableData = res.result.records
        }
      })
    },
    addGroup() {
      this.groupModel = {}
      this.addGroupVisible = true
    },
    addCopy() {
      this.excelVisible = true
    },
    handleOkExcel(data) {
      if (!data || data.length === 0) {
        this.$message.warning('请粘贴数据再导入')
        return
      }
      
      for(let i = 0;i<data.length;i++){
      if(!data[i].groupName){
          return "请输入第["+(i+1)+"]行组名称"
        }
      
        if(!data[i].userName){
          return "请输入第["+(i+1)+"]行成员名称"
        }
       
      }
      postAction(this.urls.addBatchUser, data)
        .then((res) => {
          if (res.code === 200) {
            this.excelVisible = false
            this.$message.success('导入成功')
            this.fetchList()
          } else {
            this.$message.warning('操作异常:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('操作异常:' + res.message)
        })
    },
    handleCancelExcel: function () {
      this.excelVisible = false
    },
    cancleSaveGroup() {
      this.groupModel = {}
      this.addGroupVisible = false
    },
    saveGroup() {
      this.$refs.groupForm.validate((valid) => {
        if (valid) {
          postAction(this.urls.saveGroup, this.groupModel).then((res) => {
            if (res.success) {
              this.group = res.result
              this.fetchList()
              this.$message.success('添加成功')
              this.cancleSaveGroup()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    addUser() {
      this.userModel = {}
      this.$set(this.userModel, 'groupId', this.group.id)
      // this.addUserVisible = true
      this.originTargetKeys = []
      this.$refs.userSelect.doSelect()
    },
    cancleSaveUser() {
      this.userModel = {}
      this.addUserVisible = false
    },
    selectUser(col) {
      this.originTargetKeys = []
      this.$refs.userSelect.doSelect()
    },
    setResult(result) {
      var usernames = []
      var realnames = []
      if (result != null) {
        result.forEach((item) => {
          usernames.push(item.username)
          realnames.push(item.realname)
        })

        this.userModel.userId = usernames.join(',')
        this.userModel.userName = realnames.join(',')
        postAction(this.urls.saveUser, this.userModel).then((res) => {
          if (res.success) {
            this.fetchUserList(this.group.id)
          } else {
            this.$message.error('添加成员失败')
          }
        })
      }
    },
    saveUser() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          let userIds = []
          let userNames = []
          this.userModel.userStr.forEach((user) => {
            let userStrArr = user.split('###')
            userIds.push(userStrArr[0])
            userNames.push(userStrArr[1])
          })
          this.userModel.userId = userIds.join(',')
          this.userModel.userName = userNames.join(',')
          postAction(this.urls.saveUser, this.userModel).then((res) => {
            if (res.success) {
              this.fetchUserList(this.group.id)
            } else {
              this.$message.error('添加成员失败')
            }
          })
          this.cancleSaveUser()
        }
      })
    },
    selectedGroup(select) {
      let group = this.groupList.find((item) => {
        return item.id == select.key
      })
      this.group = group
      this.defaultKeys = [this.group.id]
      this.fetchUserList(group.id)
    },
    fetchUser(val) {
      this.userList = []
      this.fetching = true
      getAction(this.urls.getUserList, { name: val }).then((res) => {
        if (res.success) {
          this.userList = res.result
          if (res.result.length > 0) {
            this.fetching = false
            res.result.forEach((it) => {
              this.userList.push({ label: it.realname, value: it.username })
            })
          }
        }
      })
    },
    selectedUser(val) {
      console.info(val)
    },
    getGroupName(record) {
      for (let group of this.groupList) {
        if (group.id == record.groupId) {
          return group.name
        }
      }
    },
    deleteGroup() {
      const that = this

      if (!!that.group) {
        that.$confirm({
          content: `是否确定删除所选定的私有组`,
          onOk: () => {
            getAction(that.urls.delGroup, { ids: that.group.id })
              .then((res) => {
                if (res.success) {
                  that.group = {}
                  that.fetchList()
                  that.$message.success(res.message)
                } else {
                  that.$message.error(res.message)
                }
              })
              .finally(() => {})
          },
        })
      } else {
        this.$message.warning('请选择需要删除的私有组')
      }
    },
    delUser() {
      const that = this
      if (this.selectedRowKeys.length > 0) {
        that.$confirm({
          content: `是否确定删除所选定的组成员`,
          onOk: () => {
            let ids = []
            that.selectedRowKeys.forEach((row) => {
              ids.push(row)
            })

            getAction(that.urls.delUser, { ids: ids.join(',') })
              .then((res) => {
                if (res.success) {
                  that.fetchUserList(that.group.id)
                  that.$message.success(res.message)
                } else {
                  that.$message.error('请选择序号删除的成员')
                }
              })
              .finally(() => {
                that.selectedRowKeys = []
              })
          },
        })
      } else {
        this.$message.warning('请选择需要删除的成员')
      }
    },
    pageChange(page) {
      this.ipagination.pageNo = page.current
      this.ipagination.currPageSize = page.pageSize
      this.ipagination.pageSize = page.pageSize
      this.ipagination.current = page.current
      this.fetchUserList(this.group.id)
    },
  },
}
</script>

<style scoped lang="less">
@import '~@assets/less/hte-main.less';
.box {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-top: 16px;
}
.box-left {
  width: 240px;
  background: #fff;
}
.box-right {
  width: calc(100% - 250px);
  background: #fff;
}
.group-header {
  height: 40px;
  line-height: 40px;
  background-color: #ccc;
  text-align: center;
  font-weight: 300;
  font-size: 24px;
  color: white;
}
.group-item {
  height: 30px;
  line-height: 30px;
  background-color: #efefef;
  text-align: left;
  font-weight: 200;
  font-size: 16px;
  cursor: pointer;
  padding-left: 10px;
  border-bottom: #ccc 1px solid;
}
.active-group {
  background-color: #ccc;
}
.btn-group {
  justify-content: flex-start;
  align-items: center;
  height: 40px;
  line-height: 40px;
}
.layout-left {
  height: calc(100vh - 240px);
}
</style>
